package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * 解决 Cookie 中含有中文信息的问题
 */
public class C10_EncoderCookie extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("C10_EncoderCookie 被调用...");

        //1.创建cookie，有中文
        /*
            I)如果直接存放中文cookie，会报错
            II)可以使用URLEncoder对中文进行编码
            III)编码后再保存即可
            IV)读取cookie时需要使用URLDecoder.decode()进行解码
         */
        String username = URLEncoder.encode("张三", "UTF-8");
        Cookie cookie = new Cookie("username", username);
        //2.保存到浏览器
        resp.setContentType("text/html;charset=utf-8");
        resp.addCookie(cookie);
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>设置cookie有效路径成功</h1>");
        writer.flush();
        writer.close();
    }
}
